<template>
  <view class="content">
    <narbar title="确认订单"></narbar>
    <!-- 地址 -->
    <view class="address">
      <view v-if="addrResult.length <= 0" style="display: flex" class="addr_bk" @click="openAddress">
        <view style="display: flex">
          <u-icon size="18" name="map"></u-icon>
          <text style="margin-left: 10rpx">请选择收货地址</text>
        </view>

        <u-icon size="14" name="arrow-right"></u-icon>
      </view>

      <view v-else style="width: 100vw">
        <view
          v-for="(item, index) in addrResult"
          class="addr_bk"
          :key="index"
          :style="{ marginBottom: index < addrResult.length - 1 ? '20rpx' : '0' }"
        >
          <!-- <u-icon size="18" name="map"></u-icon> -->
          <view style="display: flex; flex-direction: column; width: 80%" @click="openAddress">
            <view>
              <text style="font-weight: 600; font-size: 28rpx">{{ item.realName }}</text>
              <text style="margin-left: 30rpx">{{ item.phone }}</text>
            </view>
            <view class="addr_detail"> {{ item.region }}{{ item.detail }}</view>
          </view>

          <view>
            <text class="num_title">下单数量</text>
            <view style="margin-top: 10rpx">
              <u-number-box v-model="item.num" :min="0" @change="(e) => numChange(e, index)">
                <template #minus>
                  <view class="minus">
                    <u-icon name="minus" size="10"></u-icon>
                  </view>
                </template>
                <template #input>
                  <text class="input">{{ item.num }}</text>
                </template>
                <template #plus>
                  <view class="plus">
                    <u-icon name="plus" color="#FFFFFF" size="10"></u-icon>
                  </view>
                </template>
              </u-number-box>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 商品卡片 -->
    <view class="product-container" v-for="(item, index) in info" :key="index">
      <!-- 内容区 -->
      <view class="product-content">
        <view class="product-image">
          <image :src="item.skuImage"></image>
        </view>
        <view class="product-info">
          <view class="product-info-header">
            <view class="title">{{ item.goodsName }}</view>
            <view class="sku_nn">
              <view class="sku_name">{{ item.skuName }}</view>
              <view class="sku_num">×{{ buyNum }}</view>
            </view>
          </view>
        </view>

        <view class="sku_price">
          <text style="font-size: 22rpx; color: #d23000"> 实付：￥</text>
          <text class="price">{{ item.skuPresentPrice * item.num }}</text>
        </view>
      </view>
    </view>

    <view class="order_info">
      <view class="info_title">订单明细</view>
      <view class="info_item">
        <text class="info_item_title">商品总价</text>
        <text class="info_item_price">￥{{ Number(orderPrices.total).toFixed(2) }}</text>
      </view>

      <view class="info_item">
        <text class="info_item_title">运费</text>
        <text class="info_item_price">￥{{ Number(orderPrices.freight).toFixed(2) }}</text>
      </view>

      <view class="info_item">
        <text class="info_item_title">实付总价</text>
        <text class="info_item_price">￥{{ Number(orderPrices.realTotal).toFixed(2) }}</text>
      </view>
    </view>

    <view class="order_info">
      <u-input placeholder="请输入订单备注" border="surround" v-model="remark">
        <template #prefix>
          <u-text text="订单备注" margin="0 3px 0 0" type="tips"></u-text>
        </template>
      </u-input>
    </view>

    <view class="pay_info">
      <view style="display: flex; align-items: center">
        <image :src="patTypeIcon" class="pay_type_icon"></image>
        <text style="font-size: 33rpx; margin-left: 10rpx">{{ appType == 0 ? "支付宝" : "微信" }}</text>
      </view>

      <view>
        <u-checkbox-group>
          <u-checkbox :key="0" :name="0" checked shape="circle" disabled />
        </u-checkbox-group>
      </view>
    </view>
  </view>

  <view class="bottom_footer">
    <view class="submit_price"
      >合计：<text class="price">￥{{ orderPrices.realTotal }}</text>
    </view>
    <view class="submit_btn" @click="submit">提交订单</view>
  </view>

  <u-modal :show="delAddrShow" title="提示" content="是否确认删除该地址" showCancelButton @confirm="delAddrConfirm" @cancel="delAddrCancel"></u-modal>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import narbar from "@/components/narbar.vue";
import { doOrderBuy, doWxBuy, doCloseOrder } from "@/utils/api";

const delAddrShow = ref(false);
const addressInfo = ref(null);
const info = ref();
const patTypeIcon = ref();
//0:支付宝 1：微信
const appType = ref(0);
const orderPrices = reactive({
  total: 0, //商品总价
  freight: 0, //运费
  realTotal: 0, //实付总价
});
const remark = ref();
// 后面页面识别出来的地址，多个
const addrResult = ref([]);

// 购买数量
const buyNum = ref(1);

onShow(() => {
  if (uni.getStorageSync(String(info.value[0].goodsId))) {
    addrResult.value = JSON.parse(uni.getStorageSync(String(info.value[0].goodsId)));
    addrResult.value.forEach((item) => {
      item.num = 1;
    });

    buyNum.value = 0;
    addrResult.value.forEach((item) => {
      buyNum.value = buyNum.value + item.num;
    });
  }
});

onLoad((option) => {
  //支付图标
  appType.value = uni.getSystemInfoSync().uniPlatform == "mp-alipay" ? 0 : 1;
  patTypeIcon.value = appType.value == 0 ? "../../static/alipay.png" : "../../static/wechat.png";
  if (uni.getStorageSync("addressInfo")) {
    addressInfo.value = uni.getStorageSync("addressInfo");
  }
  let sss = "";
  try {
    sss = decodeURIComponent(option.info);
  } catch (e) {
    sss = option.info;
  }

  info.value = JSON.parse(sss);

  // info.value.forEach((item) => {
  //   orderPrices.total += Number(item.skuPresentPrice) * buyNum.value; //总价
  // });

  // //运费
  // orderPrices.freight = Number(info.value[0].baseFreight) + Number(info.value[0].additionalFreight);
  // //实付
  // orderPrices.realTotal = (Number(orderPrices.total) + Number(orderPrices.freight)).toFixed(2);

  //计算总价
  orderPrices.total = 0;
  orderPrices.freight = 0;
  orderPrices.realTotal = 0;
  info.value.forEach((item) => {
    orderPrices.total += Number(item.skuPresentPrice) * buyNum.value;
  });

  //运费
  orderPrices.freight = Number(info.value[0].baseFreight) + Number(info.value[0].additionalFreight);
  //实付
  orderPrices.realTotal = (Number(orderPrices.total) + Number(orderPrices.freight)).toFixed(2);
});

watch(
  () => buyNum.value,
  (val) => {
    if (val) {
      //计算总价
      orderPrices.total = 0;
      orderPrices.freight = 0;
      orderPrices.realTotal = 0;
      info.value.forEach((item) => {
        orderPrices.total += Number(item.skuPresentPrice) * buyNum.value;
      });

      //运费
      orderPrices.freight = Number(info.value[0].baseFreight) + Number(info.value[0].additionalFreight);
      //实付
      orderPrices.realTotal = (Number(orderPrices.total) + Number(orderPrices.freight)).toFixed(2);
    }
  }
);

// 确认删除地址
function delAddrConfirm() {
  addrResult.value.splice(cuAddrIndex.value, 1);
  delAddrShow.value = false;
  console.log("🚀 ~ delAddrConfirm ~   addrResult.value:", addrResult.value);

  uni.setStorageSync(String(info.value[0].goodsId), JSON.stringify(addrResult.value));
}
// 关闭删除地址提示框
function delAddrCancel() {
  delAddrShow.value = false;
}

const cuAddrIndex = ref(0);
// 购买数量改变
function numChange(event, index) {
  if (event.value <= 0) {
    delAddrShow.value = true;
    cuAddrIndex.value = index;
  } else {
    addrResult.value[index].num = event.value;
  }
  buyNum.value = 0;
  addrResult.value.forEach((item) => {
    buyNum.value = buyNum.value + item.num;
  });
}

function openAddress() {
  uni.navigateTo({
    url: "/pages/goodsDetail/chooseAddr?goodsId=" + info.value[0].goodsId,
  });
  // uni.chooseAddress({
  //   success(res) {
  //     if (res.userName) {
  //       addressInfo.value = res;
  //       uni.setStorageSync("addressInfo", addressInfo.value);
  //     }
  //   },
  //   fail(e) {
  //     console.log("🚀 ~ fail ~ e:", e);
  //   },
  // });
}

function submit() {
  if (addrResult.value.length <= 0) {
    uni.showToast({
      title: "请选择收货地址",
      icon: "none",
    });
    return;
  }

  // const platform = uni.getEnv().PLATFORM;
  const platform = uni.getSystemInfoSync().uniPlatform;
  if (platform === "mp-weixin") {
    // 微信小程序
    submitWx();
  }
  if (platform === "mp-alipay") {
    // 支付宝小程序
    submitAlipay();
  }
  if (platform === "h5") {
    // Web
  }
  if (platform === "app-plus") {
    // app
  }
}

// 新微信下单接口
async function submitWx() {
  uni.showLoading();
  let skuList = [];
  info.value.forEach((item) => {
    skuList.push({
      goodsId: item.goodsId,
      skuId: item.skuId,
      skuPresentPrice: item.skuPresentPrice * 100,
      skuOriginalPrice: item.skuOriginalPrice * 100,
      skuNum: item.num,
    });
  });

  // 用于提交的地址数组
  const subAddrs = [];
  addrResult.value.forEach((item) => {
    subAddrs.push({
      goodsId: skuList[0].goodsId,
      skuId: skuList[0].skuId,
      skuPresentPrice: skuList[0].skuPresentPrice,
      skuOriginalPrice: skuList[0].skuOriginalPrice,

      consigneeName: item.realName,
      consigneePhone: item.phone,
      consigneeAddress: item.region + item.detail,
      skuNum: item.num,
    });
  });

  const type = uni.getSystemInfoSync().uniPlatform;
  let par = {
    fromType: 0, //0：私域订单；1：公域订单
    payType: type == "mp-alipay" ? 0 : 1, //0：支付宝；1：微信
    orderAmount: orderPrices.realTotal * 100, //订单总金额,单位分
    goodsAmount: orderPrices.total * 100, //商品金额
    expressAmount: orderPrices.freight * 100, //运费
    payAmount: orderPrices.realTotal * 100, //支付金额,单位分

    freightId: info.value[0].freightId, //运费模板ID
    dtoList: subAddrs,
  };
  let { code, data } = await doWxBuy(par);
  if (code == 200) {
    let accountInfo = uni.getAccountInfoSync();

    uni.requestPayment({
      provider: "wxpay",
      appId: accountInfo.miniProgram.appId,
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      paySign: data.paySign,
      // timeStamp: String(Date.now()),
      // nonceStr: "A1B2C3D4E5",
      // package: "prepay_id=wx041052533532341cdcc226a9ec95c00000",
      signType: "RSA",
      // paySign: rsaStr,
      // sign: encrypted,
      success: function (res) {
        console.log("success:" + JSON.stringify(res));
        uni.redirectTo({
          url: "/pages/goodsDetail/payResult?orderId=" + data.orderId,
        });
      },
      fail: function (err) {
        console.log(err);
        uni.navigateTo({
          url: "/pages/order/index",
        });
      },
    });
  }
  uni.hideLoading();
}

// 原支付宝老下单接口
async function submitAlipay() {
  let skuList = [];
  info.value.forEach((item) => {
    skuList.push({
      goodsId: item.goodsId,
      skuId: item.skuId,
      skuPresentPrice: item.skuPresentPrice * 100,
      skuOriginalPrice: item.skuOriginalPrice * 100,
      skuNum: item.num,
    });
  });

  const type = uni.getSystemInfoSync().uniPlatform;
  let par = {
    fromType: 0, //0：私域订单；1：公域订单
    payType: type == "mp-alipay" ? 0 : 1, //0：支付宝；1：微信
    orderAmount: orderPrices.realTotal * 100, //订单总金额,单位分
    goodsAmount: orderPrices.total * 100, //商品金额
    expressAmount: orderPrices.freight * 100, //运费
    payAmount: orderPrices.realTotal * 100, //支付金额,单位分
    consigneeName: addressInfo.value.userName, //收货人姓名
    consigneePhone: addressInfo.value.telNumber, //收货人联系方式
    consigneeAddress: addressInfo.value.detailInfo, //收货人地址
    consigneeRemark: remark.value, //收货人备注
    freightId: info.value[0].freightId, //运费模板ID
    skuList: skuList,
  };
  let { code, data } = await doOrderBuy(par);
  if (code == 200) {
    uni.requestPayment({
      provider: "alipay",
      orderInfo: data.tradeNo, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
      // orderInfo: "2023101122001409411406529490", //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
      success: function (res) {
        console.log("success:" + JSON.stringify(res));
        uni.redirectTo({
          url: "/pages/goodsDetail/payResult?orderId=" + data.orderId,
        });
      },
      fail: function (err) {
        console.log("fail:" + JSON.stringify(err));

        doCloseOrder({
          tradeNo: data.tradeNo,
        }).then((res) => {
          uni.navigateTo({
            url: "/pages/home/index",
          });
        });
      },
    });
  }
}
</script>

<style lang="scss" scoped>
.content {
  padding: 30rpx;
  font-size: 24rpx;
  background-color: #f6f6f6;
  padding-bottom: 200rpx;
}

.address {
  display: flex;
  justify-content: space-between;
  width: 100vw;
}

.product-container {
  padding: 20rpx;
  background-color: white;
  border-radius: 10rpx;
  margin: 20rpx 0;

  // 头部
  .product-header-container {
    padding: 20rpx 0;
    display: flex;
    align-items: center;

    .product-logo {
      width: 39rpx;
      height: 39rpx;
      // background-color: red;
      margin-right: 21rpx;
    }

    .product-title {
      font-size: 25rpx;
      font-weight: bold;
    }
  }

  // 内容区
  .product-content {
    position: relative;
    height: 100%;
    margin-top: 21rpx;
    display: flex;
    justify-content: space-between;

    .product-image image {
      width: 170rpx;
      height: 170rpx;
      // background-color: red;
      margin-right: 30rpx;
    }

    .product-info {
      width: calc(100% - 200rpx);
      height: 100%;

      .product-info-header {
        .title {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          font-weight: bold;
        }
      }

      // background-color: red;
    }
  }
}

.sku_name {
  font-size: 22rpx;
  color: #999999;
}

.sku_nn {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10rpx;
}

.sku_num {
  margin-right: 10rpx;
}

.price {
  font-size: 48rpx;
  color: #d23000;
  font-weight: 600;
}

.sku_price {
  position: absolute;
  right: 0;
  bottom: 0em;
}

.order_info {
  background-color: white;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.info_title {
  font-size: 33rpx;
  font-weight: 600;
  margin-bottom: 30rpx;
}

.info_item {
  height: 80rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info_item_title {
  font-size: 28rpx;
}

.info_item_price {
  font-size: 34rpx;
  font-weight: 600;
}

.pay_info {
  background-color: white;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pay_type_icon {
  width: 50rpx;
  height: 50rpx;
}

.bottom_footer {
  position: fixed;
  bottom: 0;
  width: 100vw;
  height: 150rpx;
  background-color: white;
  z-index: 999;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 0 5rpx rgba($color: #000000, $alpha: 0.3);
}

.submit_price {
  margin-left: 30rpx;
}

.submit_btn {
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 100rpx;
  background-color: red;
  color: white;
  padding-left: 40rpx;
  padding-right: 40rpx;
  padding-top: 10rpx;
  padding-bottom: 10rpx;
  margin-right: 30rpx;
}

.minus {
  width: 18px;
  height: 18px;
  border-width: 1px;
  border-color: #e6e6e6;
  border-top-left-radius: 100px;
  border-top-right-radius: 100px;
  border-bottom-left-radius: 100px;
  border-bottom-right-radius: 100px;
  justify-content: center;
  align-items: center;
  display: flex;
}

.input {
  padding: 0 10px;
  min-width: 30rpx;
  display: flex;
  text-align: center;
  justify-content: center;
}

.plus {
  width: 18px;
  height: 18px;
  background-color: #ff0000;
  border-radius: 10rpx;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  justify-content: center;
  align-items: center;
}

.addr_detail {
  margin-top: 10rpx;
  color: #b1b1b1;
  font-size: 24rpx;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 显示省略号 */
}

.addr_bk {
  background-color: white;
  // box-shadow: 0 0 3rpx rgba($color: #000000, $alpha: 0.2);
  display: flex;
  width: 87%;
  justify-content: space-between;
  padding: 20rpx;
  border-radius: 10rpx;
  align-items: center;
}

.num_title {
  font-size: 20rpx;
  color: #b1b1b1;
  margin-left: 30rpx;
}
</style>
